<template>
  <svg id="vital-text-out">
    <line
      v-for="(item, index) in lineSvg"
      :key="index"
      v-bind="item"
    />
    <template v-if="textDataSvgData.length > 0">
      <TextSvgIndex
        v-for="(item, index) in textDataSvgData"
        :key="index"
        :config="item"
      />
    </template>

    <template v-if="spo2Svg.length > 0"> 
      <Spo2TextSvg
        v-for="(item, index) in spo2Svg"
        :key="index"
        :config="item"
      />
    </template>

  </svg>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";

import TextSvgIndex from "../common/TextSvgIndex.vue";
import Spo2TextSvg from "../common/Spo2TextSvg.vue";

import moment from "moment";
import Custom_Variable from "../CUSTOM";

let props = defineProps({
  config: Object,
});

let lineSvg = ref([]);
let textDataSvgData = ref([]);
let spo2Svg = ref([]);

/**
 * 获取体温单数据
 */
let parseVitalTextOut = () => {
  let {
    config,
    data,
    items,
    keyToNumber,
    scale,
    unit,
    split,
    noHandle,
    ...ohterProps
  } = props.config;

  items = props.config.showData.items;
  data = props.config.showData.vitalTextOuts;
  scale = 1;
  unit = "mm";
  noHandle = ["日期", "表顶注释", "表底注释", "不升", "住院天数", "术后天数"];

  console.log("props.config", props.config);

  // debugger

  let vitalTextOutToConfig = config["vitalTextOutToConfig"] || {};
  let vitalShowToConfig = config["vitalShowToConfig"] || {};
  let textData = []; // 满足数据文字需求的
  let textDataSvg = []; // 绘制的svg数组
  let lineSvg = []; // 线条，特殊情况（血压）
  let spo2Svg = []; // 文字，spo2定制
  items = items || [];
  let allowSplitName = [];
  // 特殊处理 获取需要合并的值，如 入量/出量合并
  // 显示合并，但值需要分开，不然无法删除，2019年11月26日17:40:40刘伶俐修改
  for (let name in vitalTextOutToConfig) {
    let splitNames = (name || "").split("/");
    if (splitNames.length > 1) {
      allowSplitName.push(splitNames);
    }
  }
  if (allowSplitName.length > 0) {
    // items 根据cellindex分组
    let cellIndexToNameToConfig = {};
    let cellIndexToNameToDate = {};
    items.forEach((item) => {
      let showItem = item["_attr"];
      if (!cellIndexToNameToConfig[showItem.cellindex]) {
        cellIndexToNameToConfig[showItem.cellindex] = {};
      }
      if (!cellIndexToNameToDate[showItem.cellindex]) {
        cellIndexToNameToDate[showItem.cellindex] = {};
      }
      // 同一个cellIndex对应的时间可能是不一样的
      // 所以用
      cellIndexToNameToConfig[showItem.cellindex][showItem.vitalsigns] =
        showItem.vitalsignsvalues;
      cellIndexToNameToDate[showItem.cellindex][showItem.vitalsigns] =
        showItem.date;
    });

    for (let cellIndex in cellIndexToNameToConfig) {
      let config = cellIndexToNameToConfig[cellIndex];
      for (let i = 0; i < allowSplitName.length; i++) {
        let value = [];
        let nameToValue = {};
        for (let j = 0; j < allowSplitName[i].length; j++) {
          if (config[allowSplitName[i][j]] !== undefined) {
            value.push(config[allowSplitName[i][j]]);
            nameToValue[allowSplitName[i][j]] = config[allowSplitName[i][j]];
          }
        }
        const nameToDate = cellIndexToNameToDate[cellIndex];
        items.push({
          _attr: {
            vitalsigns: allowSplitName[i].join("/"),
            vitalsignsvalues: value.join("/"),
            vitalsignsoriginalvalues: "",
            cellindex: cellIndex,
            mainName: "",
            // date: cellIndexToNameToDate[cellIndex],
            names: allowSplitName[i],
            nameToValue: nameToValue,
            nameToDate: nameToDate,
            values: value,
          },
        });
      }
    }
  }

  // 特殊处理，获取所有自定义项目， 并按照自定义项目名称分割成单独的一组
  let customItems = items.filter((item) => {
    const vitalsigns = item["_attr"].vitalsigns || "";
    return vitalsigns.indexOf("自定义项") > -1 && item["_attr"].mainName;
  });
  let filterItem = items.filter((item) => {
    const vitalsigns = item["_attr"].vitalsigns || "";
    return vitalsigns.indexOf("自定义项") === -1;
  });

  // 如果用primaryNameTo对象中mainName作为key来表示唯一的话，会导致当mainName为数字时会排在前面，影响排序
  // 在分组时标识序号，供之后循环时作为自定义项目中的index排序--2019-08-20 15:12:37 刘伶俐修改
  let primaryNameTo = {};
  let primaryNameToIndex = {};
  for (let i = 0; i < customItems.length; i++) {
    const { mainName } = customItems[i]["_attr"];
    if (!primaryNameTo[mainName]) {
      primaryNameTo[mainName] = [];
      primaryNameToIndex[mainName] = Object.keys(primaryNameToIndex).length;
    }
    primaryNameTo[mainName].push(customItems[i]);
  }
  for (let mainName in primaryNameTo) {
    let lists = primaryNameTo[mainName];
    for (let i = 0; i < lists.length; i++) {
      let {
        vitalsigns,
        vitalsignsvalues,
        vitalsignsoriginalvalues,
        cellindex,
        ...other
      } = lists[i]["_attr"];
      let isUp = (vitalsigns || "").indexOf("UP") > -1;
      let isDown = (vitalsigns || "").indexOf("isDown") > -1;
      let nextStr = isUp ? "UP" : isDown ? "isDown" : "";
      filterItem.push({
        _attr: {
          ...other,
          vitalsigns: `自定义项目${
            primaryNameToIndex[mainName] || ""
          }${nextStr}`,
          vitalsignsvalues: vitalsignsvalues,
          vitalsignsoriginalvalues: vitalsignsoriginalvalues,
          cellindex: cellindex,
          mainName: mainName,
        },
      });
    }

    let config =
      vitalTextOutToConfig[`自定义项目${primaryNameToIndex[mainName] || ""}`];
    if (config) {
      // 绘制自定义项目文本 不特殊处理，懒得管了
      //const nameToUnitStr = {'胆汁': 'ml', '引流量': 'ml', '鼻饲': 'ml', '口入': 'ml', '腹围': 'cm', '胃液': 'ml'};
      const nameToUnitStr = {};
      const strNext = nameToUnitStr[mainName]
        ? `(${nameToUnitStr[mainName]})`
        : "";
      textDataSvg.push({
        style: config.style,
        x: (config.x / 2) * scale + unit,
        y: (config.y + config.cy / 2) * scale + unit,
        // fill: config.style.color,
        value: `${mainName}${strNext}`,
        tSpan: [],
      });
    }
  }
  // 特殊处理 呼吸机
  let mrItems = {};
  // 特殊处理， cellIndex和name相同的分成1组(暂时只处理name:'表顶注释')， 避免重叠显示
  // 2019年11月26日14:49:04 刘伶俐修改
  let nameIndexToItem = {};

  filterItem.forEach((element: any) => {
    let attr = element["_attr"];
    let { vitalsigns, cellindex } = attr;
    if (["表顶注释"].includes(vitalsigns) && !Custom_Variable.isEventAbreast) {
      let nameIndex = `${vitalsigns}_${cellindex}`;
      if (!nameIndexToItem[nameIndex]) {
        nameIndexToItem[nameIndex] = [];
      }
      nameIndexToItem[nameIndex].push(element);
    }
    if (cellindex > -1 && vitalsigns.indexOf("MR") > -1) {
      let name = vitalsigns.split("/")[0].split("呼吸机")[1];
      let nameIndex = `${name}_${cellindex}`;
      if (!mrItems[nameIndex]) {
        mrItems[nameIndex] = [];
      }
      attr.vitalsigns = "呼吸机";
      attr.vitalsignsvalues = name;
      mrItems[nameIndex].push(element);
    }
  });

  // 过滤掉有重叠显示的，追加在后面
  filterItem = filterItem.filter((item) => {
    let attr = item["_attr"];
    let { vitalsigns, cellindex } = attr;
    let nameIndex = `${vitalsigns}_${cellindex}`;
    return (
      !nameIndexToItem[nameIndex] ||
      (nameIndexToItem[nameIndex] && nameIndexToItem[nameIndex].length <= 1)
    );
  });

  for (let nameIndex in nameIndexToItem) {
    if (nameIndexToItem[nameIndex].length > 1) {
      let children = nameIndexToItem[nameIndex];
      // children根据时间排序
      children.sort((a, b) => {
        return moment(a["_attr"].date) - moment(b["_attr"].date);
      });
      let attr = children[0]["_attr"];
      filterItem.push({
        _attr: {
          ...attr,
          sameNameIndex: children.map((item) => {
            return item["_attr"];
          }),
        },
      });
    }
  }

  for (let nameIndex in mrItems) {
    if (mrItems[nameIndex].length > 1) {
      let children = mrItems[nameIndex];
      // children根据时间排序
      children.sort((a, b) => {
        return moment(a["_attr"].date) - moment(b["_attr"].date);
      });
      let attr = children[0]["_attr"];
      filterItem.push({
        _attr: {
          ...attr,
          sameNameIndex: children.map((item) => {
            return item["_attr"];
          }),
        },
      });
    }
  }

  // let {patientEventList} = this.props;
  let patientEventList = [];

  // 获取符合绘制条件的数据
  filterItem.forEach((element: any) => {
    let attr = element["_attr"];
    let { vitalsigns, vitalsignsvalues, mainName, cellindex, flag, ...other } =
      attr;
    let _name = JSON.parse(JSON.stringify(vitalsigns));

    //呼吸机 在下方列表展示 特殊处理
    if (
      vitalsigns.includes("呼吸机") &&
      vitalsigns &&
      vitalsigns.split("呼吸机")[1]
    ) {
      vitalsignsvalues = vitalsigns && vitalsigns.split("呼吸机")[1];
      vitalsigns = "呼吸机";
    }

    if (vitalTextOutToConfig[vitalsigns]) {
      let name = vitalsigns;
      if (name.indexOf("自定义项目") > -1) {
        name = mainName;
      }
      name = (name || "").replace("UP", "").replace("DOWN", "");
      if (name === "表顶注释" || name === "表底注释") {
        name = "事件";
      }
      // 体温类型有拒测时，name显示体温
      // 病人事件列表不存在时，默认显示为体温
      let isInPatientEvent =
        (patientEventList || []).filter(
          (item) => item.label === vitalsignsvalues
        ).length > 0;

      if (name === "表底注释" && !isInPatientEvent) {
        // 体温不升
        name = "体温";
      }

      textData.push({
        config: vitalTextOutToConfig[vitalsigns],
        data: attr,
        value: vitalsignsvalues,
        cellIndex: cellindex,
        name: name,
        flag: name === "事件" ? flag || 2 : flag,
        _name: _name,
        ...other,
      });
    }
  });

  // 存放group-name对应的/
  const XYToGroupName = {};
  // 绘制符合条件的数据
  let newTextData = textData;
  let arr = [];
  if (Custom_Variable.isEventAbreast) {
    let eventGroup = textData.filter((f) => f._name === "表顶注释") || [];
    if (eventGroup.length > 1)
      eventGroup.sort(
        (a, b) => moment(a.date).millisecond() - moment(b.date).millisecond()
      );
    const noEventGroupp = textData.filter((f) => f._name !== "表顶注释") || [];
    newTextData = [...noEventGroupp, ...eventGroup];
  }

  for (let i = 0; i < newTextData.length; i++) {
    // debugger
    let newTextItem = newTextData[i];
    let {
      config,
      value,
      cellIndex,
      flag,
      name,
      subItem,
      sameNameIndex,
      disScale,
      ...other
    } = newTextItem;
    let isSplit = config["split"] || false; // 用于血压根据斜线拆分

    // debugger

    // 如果血压选择了外出则不拆分
    // 如果血压仅显示类型则不拆分
    if (
      (name && name.includes("血压") && value === "外出") ||
      `${value}`.split("/").length < 2
    ) {
      isSplit = false;
    }
    let isVertical = config.align === "vertical";
    let disConfigCx = config.cx / 2;
    let groupName = config["group-name"];
    let data = newTextItem["data"] || {};
    let date = newTextItem["date"] || "";
    let _name = newTextItem["_name"] || "";
    let nameShowConfig =
      vitalShowToConfig[name] || vitalShowToConfig[data.vitalsigns] || {};
    if (
      data.disScale !== undefined &&
      nameShowConfig.columnsInDay == 6 &&
      !["呼吸"].includes(nameShowConfig.name) &&
      !nameShowConfig.noUse
    ) {
      // 备注： noUse表示尽管时间全局均分时，依旧不走该模式
      // 正常来说，只有体温脉搏心率等需要折线显示的才全局均分
      cellIndex = disScale * (7 * nameShowConfig.columnsInDay);
    }

    cellIndex = cellIndex || 0;
    //console.log({ disScale, name, vitalShowToConfig, data, newTextData:  newTextItem});

    if (isVertical) {
      // 垂直元素
      disConfigCx = !split ? config.cx / 2 : 0;
    }
    // if(name === '呼吸' || name === '呼吸机') console.log({ disConfigCx, cellIndex });
    // flag  1： 红 2 蓝
    let fillColor =
      flag == 1
        ? "rgba(255,0,0,1)"
        : flag == 2
        ? "rgba(0,0,255,1)"
        : `${flag || ""}`.indexOf("rgba") > -1
        ? flag
        : config.style.color;
    let tSpan = [];
    if (sameNameIndex) {
      // 特殊处理，病人事件（表顶注释）
      let disY = 0;

      sameNameIndex.forEach((sameNameItem: any) => {
        const { vitalsignsvalues, flag, ...otherNew } = sameNameItem;

        fillColor =
          flag == 1
            ? "rgba(255,0,0,1)"
            : flag == 2
            ? "rgba(0,0,255,1)"
            : `${flag || ""}`.indexOf("rgba") > -1
            ? flag
            : "rgba(0,0,255,1)";
        textDataSvg.push({
          ...ohterProps,
          ...other,
          ...otherNew,
          style: config.style,
          x: (config.x + disConfigCx + config.cx * cellIndex) * scale + unit,
          y: (config.y - config.cy / 2 + disY) * scale + unit,
          fill: fillColor,
          value: vitalsignsvalues,
          name: name,
          config: config,
          vitalsignsvalues: vitalsignsvalues,
          isShowBalloon: noHandle.indexOf(name) === -1,
          align: config.align === "vertical",
          tSpan: (vitalsignsvalues || "").split("").map((text, j) => {
            return {
              x:
                (config.x + disConfigCx + config.cx * cellIndex) * scale + unit,
              dy: config.cy * scale + unit,
              style: config.style,
              fill: fillColor,
              text: text,
            };
          }),
        });
        disY += vitalsignsvalues.length * config.cy;
      });
    } else if (subItem) {
      // 特殊处理， SPO2
      const vitalShowConfig = vitalShowToConfig[name] || {};
      if (name.includes("皮试") && Custom_Variable.isSkin) {
        // 皮试特殊处理， 分行展示
        /**
         * 设想从显示配置那里获取配置项
         * 目前没有获取配置项来源（皮试）
         */
        const siknArr = skinItems(newTextItem);
        siknArr.forEach((item, index) => {
          spo2Svg.push({
            ...ohterProps,
            ...other,
            style: config.style,
            x:
              (config.x +
                disConfigCx +
                config.cx * cellIndex +
                (isSplit ? 0.5 : 0)) *
                scale +
              unit,
            y:
              (config.y +
                config.cy * index +
                config.cy / 2 +
                (isVertical ? -config.cy : 0)) *
                scale +
              unit,
            fill: fillColor,
            name: name,
            config: config,
            subItem: item.subItem,
            isShowBalloon: noHandle.indexOf(name) === -1,
            ...vitalShowConfig,
          });
        });
      } else {
        spo2Svg.push({
          ...ohterProps,
          ...other,
          style: config.style,
          x:
            (config.x +
              disConfigCx +
              config.cx * cellIndex +
              (isSplit ? 0.5 : 0)) *
              scale +
            unit,
          y:
            (config.y + config.cy / 2 + (isVertical ? -config.cy : 0)) * scale +
            unit,
          fill: fillColor,
          name: name,
          config: config,
          subItem: subItem,
          isShowBalloon: noHandle.indexOf(name) === -1,
          ...vitalShowConfig,
        });
      }
    } else if (config.align === "vertical") {
      value.split("").forEach((text, j) => {
        tSpan.push({
          x: (config.x + disConfigCx + config.cx * cellIndex) * scale + unit,
          dy: config.cy * scale + unit,
          style: config.style,
          fill: fillColor,
          text: text,
        });
      });
    } else if (isSplit && !Custom_Variable.isBloodHorizontally) {
      // debugger

      let values = value.split("/");
      textDataSvg.push({
        ...ohterProps,
        ...other,
        style: {
          ...config.style,
          dominantBaseline: "alphabetic",
          textAnchor: "end",
        },
        x: (config.x + disConfigCx + config.cx * cellIndex) * scale + unit,
        y: (config.y + config.cy / 2) * scale + unit,
        fill: fillColor,
        tSpan: tSpan,
        value: values[0],
        name: name,
        config: config,
        vitalsignsvalues: value,
        isShowBalloon: noHandle.indexOf(name) === -1,
      });
      textDataSvg.push({
        ...ohterProps,
        ...other,
        style: {
          ...config.style,
          dominantBaseline: "hanging",
          textAnchor: "start",
        },
        x: (config.x + disConfigCx + config.cx * cellIndex) * scale + unit,
        y: (config.y + config.cy / 2) * scale + unit,
        fill: fillColor,
        tSpan: tSpan,
        value: values[1],
        name: name,
        config: config,
        vitalsignsvalues: value,
        isShowBalloon: noHandle.indexOf(name) === -1,
      });
      let disX = 1.8;
      let disY = 1.4;
      lineSvg.push({
        x1:
          (config.x + config.cx * cellIndex + config.cx - disX) * scale + unit,
        y1: (config.y + disY) * scale + unit,
        x2: (config.x + config.cx * cellIndex + disX) * scale + unit,
        y2: (config.y + config.cy - disY) * scale + unit,
        style: {
          stroke: fillColor || "",
          strokeWidth: 0.8,
        },
      });
    } else if (isSplit && Custom_Variable.isBloodHorizontally) {
      let font = {};
      if (name === "血压" && value.includes("(")) font = { fontSize: 7 };
      textDataSvg.push({
        ...ohterProps,
        ...other,
        style: { ...config.style, ...font },
        x: (config.x + disConfigCx + config.cx * cellIndex) * scale + unit,
        y: (config.y + config.cy / 2) * scale + unit,
        fill: fillColor,
        tSpan: tSpan,
        value: value,
        name: name,
        config: config,
        vitalsignsvalues: value,
        isShowBalloon: noHandle.indexOf(name) === -1,
      });
    } else if (name === "呼吸机") {
      let offsetX = (value || []).includes("1")
        ? moment(date).hour() * 1 - 2
        : 4;
      console.log(value, "-----");
      let x = null;
      if (value.includes("MR")) {
        x = (config.x + config.cx * cellIndex * 6) * scale + 2 + offsetX + unit;
      } else {
        x = (config.x + disConfigCx + config.cx * cellIndex) * scale + unit;
      }
      let y = null;
      textDataSvg.push({
        ...ohterProps,
        ...other,
        style: config.style,
        x,
        y: (config.y + config.cy / 2) * scale + unit,
        fill: config && config.style && config.style.color,
        tSpan: tSpan,
        value: value,
        name: name,
        config: config,
        vitalsignsvalues: value,
        isShowBalloon: noHandle.indexOf(name) === -1,
      });
    }
    if (!sameNameIndex && !subItem && !isSplit && !["呼吸机"].includes(name)) {
      let nums = cellIndex;

      if (Custom_Variable.isEventAbreast && _name === "表顶注释") {
        let num = 0;
        while (arr.includes(cellIndex + num)) num++;
        arr.push(cellIndex + num);
        nums = cellIndex + num;
        tSpan = (value || "").split("").map((text, j) => {
          return {
            x: (config.x + disConfigCx + config.cx * nums) * scale + unit,
            dy: config.cy * scale + unit,
            style: config.style,
            fill: fillColor,
            text: text,
          };
        });
        if (arr.includes(42)) {
          break;
        }
      }
      textDataSvg.push({
        ...ohterProps,
        ...other,
        style: config.style,
        x:
          (config.x + disConfigCx + config.cx * nums + (isSplit ? 0.5 : 0)) *
            scale +
          unit,
        //y: (config.y + config.cy/2+ (isVertical ? -config.cy : 0)) * scale + unit,
        y:
          (config.y +
            (name === "呼吸" ? config.cy : config.cy / 2) +
            (isVertical ? -config.cy : 0)) *
            scale +
          unit,
        fill: fillColor,
        tSpan: tSpan,
        value: value,
        name: name,
        config: config,
        vitalsignsvalues: value,
        isShowBalloon: noHandle.indexOf(name) === -1,
      });
    }

    if (groupName) {
      // 配置属性存在groupName
      const configX =
        (config["group-x"] + disConfigCx + config.cx * cellIndex) * scale +
        unit;
      const configY =
        (config.y + config.cy / 2 + (isVertical ? -config.cy : 0)) * scale +
        unit;
      if (!XYToGroupName[`${configX}-${configY}`]) {
        XYToGroupName[`${configX}-${configY}`] = true;
        textDataSvg.push({
          ...ohterProps,
          ...other,
          style: config.style,
          x: configX,
          y: configY,
          fill: fillColor,
          tSpan: [],
          value: "/",
          config: config,
          vitalsignsvalues: "/",
          isShowBalloon: false,
        });
      }
    }
  }

  // textDataSvg 过滤掉类型为身高体重值为身高体重的
  textDataSvg = textDataSvg.filter((item) => {
    return !(
      (item.name === "身高" && item.value === "身高") ||
      (item.name === "体重" && item.value === "体重")
    );
  });
  // console.log({textDataSvg, lineSvg, spo2Svg}, 'textDataSvg, lineSvg, spo2Svg');
  return {
    textDataSvg,
    lineSvg,
    spo2Svg,
  };
};

let skinItems = (record: any) => {
  const { subItem, ...other } = record;
  const skinArr = [];
  for (let i = 0; i < 2; i++) {
    const item = subItem[i];
    if (!!item) {
      skinArr.push({
        ...other,
        subItem: [item],
      });
    }
  }
  return skinArr;
};

onMounted(() => {
  let { textDataSvg, lineSvg, spo2Svg } = parseVitalTextOut();

  console.log("textDataSvg, lineSvg, spo2Svg", textDataSvg, lineSvg, spo2Svg);

  lineSvg.value = lineSvg;

  textDataSvgData.value = textDataSvg;

  console.log("textDataSvg", textDataSvgData.value.length);
});
</script>
